

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.Timer;

public class AnimatingPlayer implements ActionListener {
	
	public static final int INCOMING = 1;
	public static final int OUTCOMING = -1;
	public static final float ANIMATION_DURATION = 300f;
	public static final int ANIMATION_SLEEP = 20;
	
	private TailDialog source;
	private JWindow window;
	private AnimatingComp animatingComp;

	private Timer animationTimer;
	private long animationStart;
	private int animationDirection;
	
	public AnimatingPlayer(TailDialog source){
		this.source = source;
		animatingComp = new AnimatingComp();
		
		JPanel panel = (JPanel) source.getContentPane();
		Point p = source.getLocation();
		
		Rectangle windowRect = new Rectangle(p, panel.getSize());
		animatingComp.setSource((JComponent) source.getContentPane(),windowRect);
		window = new JWindow();
		window.setLayout(new BorderLayout());
		window.add(animatingComp);
	}
	
	public void playAnimation(){
		source.doBlock();
		window.setLocation(source.getAccordingLocation());
        window.pack();
        window.setVisible(true);
		animationStart = System.currentTimeMillis();
		if(animationTimer == null){
			animationTimer = new Timer(ANIMATION_SLEEP, this);
		}
		
		animationTimer.start();
	}

	public void actionPerformed(ActionEvent e) {
		float animationPercent = (System.currentTimeMillis() - animationStart)/ANIMATION_DURATION;
		animationPercent = Math.min(1.0f, animationPercent);
		
		if(animationDirection != INCOMING){
			animatingComp.setPercent(1-animationPercent);
		}else{
			animatingComp.setPercent(animationPercent);	
		}
		//System.out.println(animationPercent);
		window.pack();
		//System.out.println(window.size().width + " " + window.size().height);
		if(animationPercent >= 1.0f){
			stopAnimation();
			if(animationDirection == INCOMING){
				finishShowing();
			}else{
				finishClosing();
			}
		}
	
	}
	
	public void setAnimationDirection(int animationDirection) {
		this.animationDirection = animationDirection;
	}

	private void finishShowing() {
		source.setVisible(true);
	}
	
	private void finishClosing(){
	}

	private void stopAnimation(){
		animationTimer.stop();
		window.setVisible(false);
		source.cancelBlock();
	}
}
